using OkTool.Util;

namespace OkTool.IO.File
{
    public class FileNameUtil
    {
        /// <summary>
        /// unix路径分隔符
        /// </summary>
        public  static  readonly char UNIX_SEPARATOR = '/';
        
        /// <summary>
        /// windows路径分隔符
        /// </summary>
        public  static  readonly char WINDOWS_SEPARATOR = '\\';
        private static string[] SPECIAL_SUFFIX = {"tar.bz2", "tar.Z", "tar.gz", "tar.xz"};
        /// <summary>
        /// 获得文件的扩展名（后缀名），扩展名不带“.”
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns>扩展名</returns>
        public static string ExtName(string fileName)
        {
            if (fileName == null)
            {
                return null;
            }

            int index = fileName.LastIndexOf(StrUtil.DOT);
            if (index == -1)
            {
                return string.Empty;
            }
            else
            {
                // issue#I4W5FS@Gitee
                int secondToLastIndex = fileName.Substring(0, index).LastIndexOf(StrUtil.DOT);
                string substr = secondToLastIndex == -1 ? fileName.Substring(index) : fileName.Substring(secondToLastIndex + 1);

                if (StrUtil.ContainsAny(substr, SPECIAL_SUFFIX))
                {
                    return substr;
                }

                string ext = fileName.Substring(index + 1);
                // 扩展名中不能包含路径相关的符号
                return StrUtil.ContainsAny(ext, UNIX_SEPARATOR, WINDOWS_SEPARATOR) ? string.Empty : ext;
            }
        }
    }
}